package com.xw.screen.capture.util;

import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;

/**
 * @author xiongwei_vendor
 * @date 2020/9/27 18:05
 */
@Slf4j
public class NumberUtil<T> {

    /**
     * 字符串转数字
     * @param numberValue 字符串形式数字
     * @param defaultT 默认值，字符串转换失败时的默认值
     * @param targetClass 类型：如Long、Integer
     * @param <T> 泛型
     * @return 数字，转换失败则默认是defaultT
     */
    public static <T> T convertStringToNumber(String numberValue, T defaultT, Class<T> targetClass) {
        try {
            return NumberUtil.convertStringToNumber(numberValue,targetClass);
        } catch (NumberFormatException ignored) {
        }
        return defaultT;
    }

    /**
     * 字符串转数字
     * @param numberValue 字符串形式数字
     * @param targetClass 类型：如Long、Intee
     * @param <T> 泛型
     * @return 数字
     * @throws NumberFormatException 转换失败抛出异常
     */
    public static <T> T convertStringToNumber(String numberValue, Class<T> targetClass) throws NumberFormatException {
        T value = null;
        if (Byte.class == targetClass) {
            value = targetClass.cast(Byte.parseByte(numberValue));
        } else if (Short.class == targetClass) {
            value = targetClass.cast(Short.parseShort(numberValue));
        } else if (Long.class == targetClass) {
            value = targetClass.cast(Long.parseLong(numberValue));
        } else if (Float.class == targetClass) {
            value = targetClass.cast(Float.parseFloat(numberValue));
        } else if (Double.class == targetClass) {
            value = targetClass.cast(Double.parseDouble(numberValue));
        } else if (Integer.class == targetClass){
            value = targetClass.cast(Integer.parseInt(numberValue));
        } else if (BigDecimal.class == targetClass) {
            value = targetClass.cast(new BigDecimal(numberValue));
        }
        return value;
    }

}
